import { computed, ref, readonly } from 'vue'
import ServicePrice from '@/api/client/servicePrice.js'
import store from '@/store'
const quoteApply = {}
quoteApply.loaded = ref(false)
quoteApply.raw = ref({
  clientInfo: {}
})
quoteApply.transformed = ref({
  clientInfo: {}
})
export function useQuoteApply(applyId, resolve = () => {}) {
  if (!quoteApply.loaded.value) {
    getData(applyId, resolve)
  } else {
    resolve({
      raw: readonly(quoteApply.raw),
      transformed: readonly(quoteApply.transformed)
    })
  }
  const reload = getData.bind(this, applyId, resolve)
  return {
    quoteApply: {
      raw: readonly(quoteApply.raw),
      transformed: readonly(quoteApply.transformed),
      loaded: readonly(quoteApply.loaded)
    },
    reload
  }
}
function getData(applyId, resolve) {
  quoteApply.loaded.value = false
  ServicePrice.getQuoteApply(applyId).then(async ({ data }) => {
    quoteApply.raw.value = data
    const dict = ref(computed(() => store.state.dict))
    await store.dispatch('dict/getCountriesOrRegions')
    await store.dispatch('dict/getCurrencies')
    await store.dispatch('dict/getBusinessAreas')
    quoteApply.loaded.value = true
    resolve({
      raw: readonly(quoteApply.raw),
      transformed: readonly(quoteApply.transformed)
    })
    if (Object.keys(quoteApply.raw.value.clientInfo).length > 0) {
      const countryOrRegion = dict.value.countriesOrRegions.find(
        countryOrRegion => countryOrRegion.value === quoteApply.raw.value.clientInfo.countryID
      )
      quoteApply.transformed.value.clientInfo.countryID = countryOrRegion
        ? countryOrRegion.text
        : quoteApply.raw.value.clientInfo.countryID
      const currency = dict.value.currencies.find(
        currency => currency.value === quoteApply.raw.value.clientInfo.currencyID
      )
      quoteApply.transformed.value.clientInfo.currencyID = currency
        ? currency.text
        : quoteApply.raw.value.clientInfo.currencyID
      const businessArea = dict.value.businessAreas.find(
        businessArea => businessArea.value === quoteApply.raw.value.clientInfo.businessDirection
      )
      quoteApply.transformed.value.clientInfo.businessDirection = businessArea
        ? businessArea.text
        : quoteApply.raw.value.clientInfo.businessDirection
    }
  })
}
